package com.example.server.controller;

import com.example.server.entity.User;
import com.example.server.entity.Writer;
import com.example.server.service.UserService;
import com.example.server.service.WriterService;
import com.example.server.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users") // 确保路径正确
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private WriterService writerService;

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody User user) {
        if (userService.isUsernameTaken(user.getUsername())) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("用户名已存在");
        }

        userService.insertUser(user);
        return ResponseEntity.ok("注册成功");
    }


    @GetMapping("/me")
    public User getCurrentUser(@RequestHeader("Authorization") String token) throws Exception {
        String tokenUsername = JwtUtil.getUsernameFromToken(token.substring(7)); // 去掉"Bearer "
        User user = userService.getUserByUsername(tokenUsername);
        if (user == null) {
            throw new Exception("用户不存在");
        }
        return user;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable int id) throws Exception {
        return userService.getUserById(id);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @PostMapping
    public void insertUser(@RequestBody User user) {
        userService.insertUser(user);
    }

    @PutMapping("/{id}")
    public String updateUser(@PathVariable int id, @RequestBody User user, @RequestHeader("Authorization") String token) throws Exception {
        String tokenUsername = JwtUtil.getUsernameFromToken(token.substring(7)); // 去掉"Bearer "
        User currentUser = userService.getUserByUsername(tokenUsername);
        if (currentUser == null || currentUser.getIduser() != id) {
            throw new Exception("无权限操作");
        }
        user.setIduser(id);
        userService.updateUser(user);
        return "用户信息已更新";
    }

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable int id, @RequestHeader("Authorization") String token) throws Exception {
        String tokenUsername = JwtUtil.getUsernameFromToken(token.substring(7)); // 去掉"Bearer "
        User currentUser = userService.getUserByUsername(tokenUsername);
        if (currentUser == null || currentUser.getIduser() != id) {
            throw new Exception("无权限操作");
        }
        userService.deleteUser(id);
        return "用户已删除";
    }
}
